package com.typy.www.tpay.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.Browser;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.typy.www.tpay.BuildConfig;
import com.typy.www.tpay.R;
import com.typy.www.tpay.ui.acitivity.ImageAddActivity;
import com.typy.www.tpay.ui.view.LoadingView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * UI界面的辅助信息
 *
 * @author yj
 */
public class UiHelper {

    private static Toast toast;
    public static int REQUEST_CODE_BROWSE_IMAGE = 100;
    public static int REQUEST_CODE_SELECTED_IMAGE = REQUEST_CODE_BROWSE_IMAGE + 1;
    public static int REQUEST_CODE_TAKE_PHOTO = REQUEST_CODE_BROWSE_IMAGE + 2;
    public static int REQUEST_CODE_CROP_IMAGE = REQUEST_CODE_BROWSE_IMAGE + 3;

    public static void showToast(Context context, int msgResId) {
        String msg = context.getString(msgResId);
        showToast(context, msg);
    }

    public static void showToast(Context context, String msg) {
        showToast(context, msg, 0);
    }

    public static void showToast(Context context, String msg, int drawableResId) {
        TextView tv = new TextView(context);
        tv.setBackgroundResource(R.drawable.toast_bg);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        tv.setPadding(24, 24, 24, 24);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv.setTextColor(context.getResources().getColor(R.color.app_toast_text_color));
        tv.setText(msg);
        if (drawableResId != 0) {
            tv.setCompoundDrawablePadding(20);
            tv.setCompoundDrawablesWithIntrinsicBounds(drawableResId, 0, 0, 0);
        }
        if (toast == null) {
            toast = new Toast(context);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setView(tv);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setView(tv);
        }
        toast.show();
    }

    public static void showToast(Context context, String msg, boolean isSuccese) {
        TextView tv = new TextView(context);
        tv.setBackgroundResource(R.drawable.toast_bg);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        tv.setPadding(24, 24, 24, 24);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv.setTextColor(context.getResources().getColor(R.color.app_toast_text_color));
        tv.setText(msg);
        if (isSuccese) {
            tv.setCompoundDrawablePadding(20);
            tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ok, 0, 0, 0);
        } else {
            tv.setCompoundDrawablePadding(20);
            tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.error, 0, 0, 0);
        }
        if (toast == null) {
            toast = new Toast(context);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setView(tv);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setView(tv);
        }
        toast.show();
    }

    public interface TakePhotoListener {
        public void onBeforeTakePhoto(boolean isThumb, File hdFile);
    }

    private static PopupWindow mPopupWindow;

    public static void showPhotoActionDlg(final Activity act, View parent,
                                          final int maxCount, final ArrayList<File> selectedPhotoList,
                                          final TakePhotoListener listener) {
        View contentView = LayoutInflater.from(parent.getContext()).inflate(R.layout.photo_action_selector, null);
        View btnTakePhoto = contentView.findViewById(R.id.btn_take_photo);
        View btnSelect = contentView.findViewById(R.id.btn_select_from_album);
        View btnCancel = contentView.findViewById(R.id.btn_cancel);

        btnTakePhoto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                takePhoto(act, listener);
            }

        });

        btnSelect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                ImageAddActivity.addPhoto(act, REQUEST_CODE_SELECTED_IMAGE, maxCount, selectedPhotoList);
            }

        });

        btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dismissPopupDlg();
            }
        });

        mPopupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(parent.getResources(), (Bitmap) null));
        mPopupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 拍照
     */
    public static void takePhoto(Activity act, TakePhotoListener listener) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Logutil.print("拍照1");
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Logutil.print("拍照2");
            File path = FileUtils.getSdCameraPath();
            File hdFile = new File(path, "Sy" + System.currentTimeMillis() + ".jpg");
            Uri uri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                uri = FileProvider.getUriForFile(act, BuildConfig.APPLICATION_ID + ".fileProvider", hdFile);
                Logutil.print("拍照3");
            } else {
                uri = Uri.fromFile(hdFile);
                Logutil.print("拍照4");
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            if (listener != null)
                listener.onBeforeTakePhoto(false, hdFile);
        } else {
            UiHelper.showToast(act, "没有插入SD卡,不能拍摄高清图片,只能拍摄小图!");
            if (listener != null)
                listener.onBeforeTakePhoto(true, null);
//            }
        }
        Logutil.print("返回值"+intent.getData());
        act.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
    }

    public static void dismissPopupDlg() {
        if (mPopupWindow != null )
            try {
                mPopupWindow.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    //    public static void setImage(File file, ImageView view, ProgressBar progress) {
//        OpenApi.loadImage(file, view, progress);
//    }
    public static void setImage(int resid, ImageView view, ProgressBar progress) {
        if (progress != null)
            progress.setVisibility(View.VISIBLE);
        view.setTag(resid);
        view.setImageResource(resid);
        if (progress != null)
            progress.setVisibility(View.GONE);
    }
    public static void setImage(File file, ImageView view, ProgressBar progress) {
       loadImage(file, view, progress);
    }
    public static void setImage(String url, ImageView view, ProgressBar progress) {
        loadImage(url, view, progress);
    }
    /**
     * 加载指定url的图片，并设置ImageView
     *
     * @param url
     * @param view
     */
    public static void loadImage(String url, final ImageView view,
                                 final ProgressBar pb) {
//        String imgUrl = ApiUrl.getPicUrl(url);
//        if (imgUrl == null || imgUrl.trim().length() == 0)
//            return;
//        int width = view.getWidth();
//        int height = view.getHeight();
//        ScaleType scaleType = view.getScaleType();
//
//        boolean wrapWidth = false, wrapHeight = false;
//        if (view.getLayoutParams() != null) {
//            wrapWidth = view.getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT;
//            wrapHeight = view.getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT;
//        }
//
//        int maxWidth = wrapWidth ? 0 : width;
//        int maxHeight = wrapHeight ? 0 : height;
//        view.setTag(imgUrl);
//        ImageLoader.ImageListener listener = new ImageLoader.ImageListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                if (pb != null)
//                    pb.setVisibility(View.GONE);
//            }
//
//            @Override
//            public void onResponse(final ImageLoader.ImageContainer response,
//                                   boolean isImmediate) {
//                Object tag = view.getTag();
//                if (tag == null || !(tag instanceof String))
//                    return;
//                String imgUrl = (String) tag;
//                if (response.getRequestUrl().equals(imgUrl)) {
//                    if (response.getBitmap() != null) {
//                        view.setImageBitmap(response.getBitmap());
//                        if (pb != null)
//                            pb.setVisibility(View.GONE);
//                    } else {
//                        view.setImageBitmap(((BitmapDrawable) view.getContext().getResources().getDrawable(R.drawable.default_pic)).getBitmap());
//                    }
//                } else {
//                    view.setImageBitmap(((BitmapDrawable) view.getContext().getResources().getDrawable(R.drawable.default_pic)).getBitmap());
//                }
//            }
//
//        };
//        if (pb != null)
//            pb.setVisibility(View.VISIBLE);
////		Log.e("loadImage(url,view,pb)", gImageLoader.isCached(imgUrl, maxWidth, maxHeight, scaleType)+imgUrl);
//        gImageLoader.get(imgUrl, listener, maxWidth, maxHeight, scaleType, isFresh);
    }

    /**
     * 加载指定文件的图片，并设置ImageView
     *
     * @param file
     * @param view
     * @param pb
     */
    public static void loadImage(File file, final ImageView view,
                                 final ProgressBar pb) {
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        int width = view.getWidth();
        int height = view.getHeight();
        if (width == 0 && lp != null) {
            if (lp.width == ViewGroup.LayoutParams.MATCH_PARENT)
                width = ((View) view.getParent()).getWidth();
            else
                width = lp.width;
        }
        if (height == 0 && lp != null) {
            if (lp.height == ViewGroup.LayoutParams.MATCH_PARENT)
                height = ((View) view.getParent()).getHeight();
            else
                height = lp.height;
        }

        boolean wrapWidth = false, wrapHeight = false;
        if (lp != null) {
            wrapWidth = lp.width == ViewGroup.LayoutParams.WRAP_CONTENT;
            wrapHeight = lp.height == ViewGroup.LayoutParams.WRAP_CONTENT;
        }

        int maxWidth = wrapWidth ? 0 : width;
        int maxHeight = wrapHeight ? 0 : height;
        if (maxWidth <= 0)
            maxWidth = GlideUtils.getInstance().mScreenWidth;
        if (maxHeight <= 0)
            maxHeight = GlideUtils.getInstance().mScreenHeight;
        loadImage(file, view, maxWidth, maxHeight, pb);
    }
    /**
     * 加载指定文件的图片，并设置ImageView
     *
     * @param file
     * @param view
     * @param pb
     */
    public static void loadImage(File file, final ImageView view, int maxWidth,
                                 int maxHeight, final ProgressBar pb) {
        if (maxWidth == 0 && maxHeight == 0)
            return;
        // if (maxWidth > mScreenWidth)
        // maxWidth = mScreenWidth / 2;
        // if (maxHeight > mScreenHeight)
        // maxHeight = mScreenHeight / 2;
        ScaleType scaleType = view.getScaleType();
        view.setTag(file);
        if (pb != null)
            pb.setVisibility(View.VISIBLE);

        Bitmap bitmap = null;
        try {
            bitmap = getBitmap(file, maxWidth, maxHeight, scaleType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bitmap != null) {
            Object tag = view.getTag();
            if (tag == null || !(tag instanceof File))
                return;
            view.setImageBitmap(bitmap);
        }

        if (pb != null)
            pb.setVisibility(View.GONE);
    }


    private static Bitmap getBitmap(File file, int maxWidth, int maxHeight,
                                    ScaleType scaleType) {
        String filename = file.getAbsolutePath();
        String key = new StringBuilder(filename.length() + 12).append("#W")
                .append(maxWidth).append("#H").append(maxHeight).append("#S")
                .append(scaleType.ordinal()).append(filename).toString();
        Bitmap bitmap =  GlideUtils.getInstance().getImageMemCache().get(key);
        if (bitmap != null)
            return bitmap;

        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        int desiredWidth = getResizedDimension(maxWidth, maxHeight,
                actualWidth, actualHeight, scaleType);
        int desiredHeight = getResizedDimension(maxHeight, maxWidth,
                actualHeight, actualWidth, scaleType);

        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth,
                actualHeight, desiredWidth, desiredHeight);
        // bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),
        // decodeOptions);
        Bitmap tempBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),
                decodeOptions);
        if (tempBitmap != null
                && (tempBitmap.getWidth() > desiredWidth || tempBitmap
                .getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth,
                    desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
        if (bitmap != null)
            GlideUtils.getInstance().getImageMemCache().put(key, bitmap);
        return bitmap;
    }

    private static int getResizedDimension(int maxPrimary, int maxSecondary,
                                           int actualPrimary, int actualSecondary, ScaleType scaleType) {

        // If no dominant value at all, just return the actual.
        if ((maxPrimary == 0) && (maxSecondary == 0)) {
            return actualPrimary;
        }

        // If ScaleType.FIT_XY fill the whole rectangle, ignore ratio.
        if (scaleType == ScaleType.FIT_XY) {
            if (maxPrimary == 0) {
                return actualPrimary;
            }
            return maxPrimary;
        }

        // If primary is unspecified, scale primary to match secondary's scaling
        // ratio.
        if (maxPrimary == 0) {
            double ratio = (double) maxSecondary / (double) actualSecondary;
            return (int) (actualPrimary * ratio);
        }

        if (maxSecondary == 0) {
            return maxPrimary;
        }

        double ratio = (double) actualSecondary / (double) actualPrimary;
        int resized = maxPrimary;

        // If ScaleType.CENTER_CROP fill the whole rectangle, preserve aspect
        // ratio.
        if (scaleType == ScaleType.CENTER_CROP) {
            if ((resized * ratio) < maxSecondary) {
                resized = (int) (maxSecondary / ratio);
            }
            return resized;
        }

        if ((resized * ratio) > maxSecondary) {
            resized = (int) (maxSecondary / ratio);
        }
        return resized;
    }
    private static int findBestSampleSize(int actualWidth, int actualHeight,
                                          int desiredWidth, int desiredHeight) {
        double wr = (double) actualWidth / desiredWidth;
        double hr = (double) actualHeight / desiredHeight;
        double ratio = Math.min(wr, hr);
        float n = 1.0f;
        while ((n * 2) <= ratio) {
            n *= 2;
        }

        return (int) n;
    }

    private static LoadingView loading;
    public static void showLoading(Context context){
        loading = new LoadingView(context, R.style.CustomDialog);
        loading.show();
    }
    public static void hideLoading(){
        if(null!=loading){
            new Handler().postDelayed(new Runnable() {//定义延时任务模仿网络请求
                @Override
                public void run() {
                    loading.dismiss();//3秒后调用关闭加载的方法
                }
            }, 500);
        }
    }
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;

    private static final int MIN_CLICK_DELAY_TIME3 = 3000;
    private static final int MIN_CLICK_DELAY_TIME2= 500;
    private static long lastClickTime;

    public static boolean isFastClick1000() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }
    public static boolean isFastClick500() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME2) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }
    public static boolean isFastClick3000() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME3) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

}
